package com.aclyyx.mi.display.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.List;

public class ServerThread extends Thread {

	private Param param;
	private List<Connect> connects;
	private Socket s = null;
	private ServerSocket ss = null;
	private PrintWriter out = null;
	
	public ServerThread(Param param, List<Connect> connects) {
		this.param = param;
		this.connects = connects;
	}
	
	public void stopServer() {
		if (s != null) {
			try {
				s.close();
			} catch (IOException e) {
			}
			s = null;
		}
		if (ss != null) {
			try {
				ss.close();
			} catch (IOException e) {
			}
			ss = null;
		}
	}
	
	public void run() {

		BufferedReader in = null;
		PrintWriter out = null;
		try {

			ss = new ServerSocket(param.getPort());
			String line = "";
			int width = 0;
			int height = 0;
			while (param.isStartFlag()) {
				try {
					s = ss.accept();
				} catch (Exception e) {
					break;
				}
				
				if (param.isGoFlag()) {
					out = new PrintWriter(s.getOutputStream(),true);
					out.println(param.runtime);
					out.flush();
					out.close();
					s.close();
					out = null;
					s = null;
					
				} else {
					in = new BufferedReader(new InputStreamReader(s.getInputStream()));
					out = new PrintWriter(s.getOutputStream(),true);
					out.println(param.getSize());
					out.println(param.getS());
					line = in.readLine();
					width = Integer.valueOf(line);
					line = in.readLine();
					height = Integer.valueOf(line);
					
					Connect conn = new Connect();
					conn.socket		= s;
					conn.beginTime	= new Date();
					conn.width = width;
					conn.height = height;
					conn.flagGo		= false;
					connects.add(conn);
					new SocketThread(connects, conn, param).start();
					
					try {Thread.sleep(25);} catch (Exception e) {}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
				in = null;
			}
			if (out != null) {
				out.close();
				out = null;
			}
			if (s != null) {
				try {
					s.close();
				} catch (IOException e) {
				}
				s = null;
			}
			if (ss != null) {
				try {
					ss.close();
				} catch (IOException e) {
				}
				ss = null;
			}
		}
	}
}
